package com.epam.zhilko.util;

import com.epam.zhilko.entity.Employee;

import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import org.apache.log4j.Logger;
/**
 * Created with IntelliJ IDEA.
 * User: admin
 * Date: 11/27/13
 * Time: 11:39 AM
 * To change this template use File | Settings | File Templates.
 */

public class DAO {

    //@PersistenceContext (unitName = "projectPersistence")
    private EntityManager em = Persistence.createEntityManagerFactory("projectPersistence").createEntityManager();
    private CriteriaBuilder cb;
    private static final Logger LOG = org.apache.log4j.Logger.getLogger(DAO.class);

    public Employee findEmployeeByID(int id) {
        Employee emp = null;
        try {
            em.getTransaction().begin();
            LOG.info("Begin transaction");
            cb = em.getCriteriaBuilder();
            CriteriaQuery<Employee> c = cb.createQuery(Employee.class);
            Root<Employee> employee = c.from(Employee.class);

            c.select(employee).where(cb.equal(employee.get("id"), id));

            TypedQuery<Employee> tq = em.createQuery(c);
            emp = tq.getSingleResult();
            em.getTransaction().commit();
            LOG.info("Commit transaction. Employee name " + emp.getName());
            return emp;
        } catch (Exception e) {
            em.getTransaction().rollback();
            LOG.error("Transaction rollback");
            e.printStackTrace();
        }
       return emp;
    }


}
